#include "tcpbase.h"
#include <QDebug>

TcpBase::TcpBase(QObject *parent): QObject{parent}
{
    socket = new QTcpSocket();
    socket->abort();
}

bool TcpBase::closeConnetion(void){
    socket->disconnectFromHost();
    socket->close();
    socket->abort();
    return socket->state() == QAbstractSocket::UnconnectedState \
           || socket->waitForDisconnected(1000);
}

void TcpBase::onRecvMsg(void){
    QByteArray msg = socket->readAll();
    if(msg.isEmpty()){
        return;
    }
    qDebug() << QString(msg);
    QList<CommonMessage> msgs = CommonMessage::stringToMessage(QString(msg));
    for(CommonMessage msg : msgs){
        emit sendMsgToMain(source, msg);
    }

}

bool TcpBase::isOpen(){
    return socket->isOpen();
}

void TcpBase::socketErrorHandler(QAbstractSocket::SocketError){
    switch(socket->error())
    {
        case QAbstractSocket::RemoteHostClosedError: //TCP远端断开
        {
            QString hostAddress = socket->QAbstractSocket::peerAddress().toString();

            disconnect(socket, SIGNAL(errorOccurred(QAbstractSocket::SocketError)), this, SLOT(socketErrorHandler(QAbstractSocket::SocketError)));
            CommonMessage msg = CommonMessage(DisConnection, hostAddress);
            emit sendMsgToMain(source, msg);
            break;
        }
        default:
        {
            CommonMessage msg = CommonMessage(ErrConnection, socket->errorString());
            emit sendMsgToMain(source, msg);
            break;
        }
    }
}

void TcpBase::sendMsg(QString msg){
    if(socket && this->isOpen()){
        socket->write(msg.toLocal8Bit().constData());
    }
}
